package com.cq.controller;

import com.cq.pojo.*;
import com.cq.service.MailService;
import com.cq.service.MeetingService;
import com.cq.service.UserService;
import com.cq.utils.PushAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @Author: 悠久的苍穹
 * @Date: 2021/1/25 14:21
 * @Description: 会议控制层
 * @Version: 1.0
 */
@Controller
public class MeetingController {


    @Autowired
    MeetingService meetingService;
    @Autowired
    MailService mailService;
    @Autowired
    UserService userService;

    @ResponseBody
    @PostMapping("/applyMeeting")
    public Result applyMeeting(@RequestBody Map<String,Object> map) throws Exception {
        Result result = new Result();
        String title = map.get("title").toString();
        String content = map.get("content").toString();
        String start = map.get("start").toString();
        String end = map.get("end").toString();
        String img = map.get("img").toString();
        Integer type = Integer.parseInt(map.get("type").toString());
        String organizer = map.get("organizer").toString();
        String uuid = map.get("uuid").toString();
        Meeting meeting = new Meeting();
        meeting.setTitle(title);
        meeting.setContent(content);
        meeting.setStart(start);
        meeting.setEnd(end);
        meeting.setImg(img);
        meeting.setType(type);
        meeting.setIshot(0);
        meeting.setOrganizer(organizer);
        meeting.setStatus(0);
        System.out.println(meeting);
        int i = meetingService.addMeeting(meeting);
        if(i==1){
            int meeting_id = meetingService.findMeeting(meeting);
            meetingService.addUserMeeting(uuid,meeting_id);
            result.setCode(200);
            result.setMsg("申请成功，请等待结果");
        }else{
            result.setCode(500);
            result.setMsg("申请失败，请重新填写");
        }
        return result;
    }

    @ResponseBody
    @GetMapping("/getMeetings")
    public Result getMeetings(@RequestParam int page,
                               @RequestParam int limit) {
        Result result = new Result();
        int count = meetingService.getCount();
        List<Meeting> meetingList = meetingService.getMeetings(page,limit);
        result.setCode(0);
        result.setCount(count);
        result.setData(meetingList);
        result.setMsg("查询成功");
        return result;
    }

    @GetMapping("/editMeetingUI/{id}")
    public String editMeetingUI(@PathVariable("id") int id, Model model){
        Meeting meeting = meetingService.getMeetingById(id);
        model.addAttribute("meeting",meeting);
        return "app/meeting/meeting/content";
    }


    @ResponseBody
    @GetMapping("/meeting/sendMeetingFailMessage")
    public Result sendMeetingFailMessage(String meetingId,String value) {
        Result result = new Result();
        User user = meetingService.findUserByMeetingId(meetingId);
        if(user!=null){
            result.setCode(200);
            mailService.sendSimpleTextMailActual("申请结果","申请不通过，"+value+"，请重新申请",new String[]{user.getEmail()},new String[]{"18120691853@163.com"},null,null);
        }else {
            result.setCode(500);
        }
        return result;
    }


    @ResponseBody
    @GetMapping("meeting/updateMeetingAndRoom")
    public Result updateMeetingAndRoom(String meetingId,String roomId) {
        Result result = new Result();
        User user = meetingService.findUserByMeetingId(meetingId);
        Room room = meetingService.findRoomById(roomId);
        Meeting meeting = meetingService.getMeetingById(Integer.parseInt(meetingId));
        if(room==null){
            Meeting meeting2 = new Meeting();
            meeting2.setId(Integer.parseInt(meetingId));
            meetingService.updateMeetingStatus(meeting2);
            if(meeting.getType()==0){
                String rtmp_url = "rtmp://push.cyansg.top/live/"+roomId+"?"+PushAddress.getSafeUrl(roomId,PushAddress.getNextThreeDay(new Date()));
                String liu = roomId+"?"+PushAddress.getSafeUrl(roomId,PushAddress.getNextThreeDay(new Date()));
                Room room1 = new Room(Integer.parseInt(roomId),meeting.getTitle(),rtmp_url,"wss://47.92.83.43/webSocket/chat/"+roomId,null);
                meetingService.addRoom(room1);
                meetingService.addMeetingRoom(Integer.parseInt(meetingId),Integer.parseInt(roomId));
//                mailService.sendSimpleTextMailActual("申请结果","您的<"+meeting.getTitle()+">申请通过,推流地址为:"+rtmp_url+"您可以使用obs进行推流，直播间地址为:"+"http://cqcq123.cn.utools.club/rtmp/"+roomId,new String[]{user.getEmail()},new String[]{"18120691853@163.com"},null,null);
                mailService.sendSimpleTextMailActual("申请结果","您的<"+meeting.getTitle()+">申请通过,推流地址为:"+rtmp_url+"您可以使用obs进行推流，url为rtmp://push.cyansg.top/live/，流名称为"+liu+"，直播间地址为:"+"https://www.cyansg.top/rtmp/"+roomId,new String[]{user.getEmail()},new String[]{"18120691853@163.com"},null,null);
            }else{
                Room room2 = new Room(Integer.parseInt(roomId),meeting.getTitle(),null,null,roomId);
                meetingService.addRoom(room2);
                meetingService.addMeetingRoom(Integer.parseInt(meetingId),Integer.parseInt(roomId));
//                mailService.sendSimpleTextMailActual("申请结果","您的<"+meeting.getTitle()+">申请通过，视频会议地址为:https://cqcq123.cn.utools.club/webrtc/。用户名请填写您的微信名，房间号为："+roomId,new String[]{user.getEmail()},new String[]{"18120691853@163.com"},null,null);
                mailService.sendSimpleTextMailActual("申请结果","您的<"+meeting.getTitle()+">申请通过，视频会议地址为:https://www.cyansg.top/webrtc/。用户名请填写您的微信名，房间号为："+roomId,new String[]{user.getEmail()},new String[]{"18120691853@163.com"},null,null);
            }
            result.setCode(200);
        }else{
            result.setCode(500);
        }
        return result;
    }



    @ResponseBody
    @GetMapping("/getMeetingsByWx")
    public Result getMeetingsByWx(){
        Result result = new Result();
        List<Meeting> meetingList = meetingService.getAllMeetings();
        result.setCode(200);
        result.setData(meetingList);
        result.setMsg("查询成功");
        return result;
    }

    @ResponseBody
    @GetMapping("/getMeetingsById/{id}")
    public Result getMeetingsById(@PathVariable("id") String id){
        Result result = new Result();
        Meeting meeting = meetingService.getMeetingById(Integer.parseInt(id));
        List<Meeting> meetingList = new ArrayList<>();
        meetingList.add(meeting);
        result.setCode(200);
        result.setData(meetingList);
        result.setMsg("查询成功");
        return result;
    }

    @ResponseBody
    @GetMapping("/getRtmpUrlByMeetingId/{id}")
    public Result getRtmpUrlByMeetingId(@PathVariable("id") String id){
        Result result = new Result();
        String rtmp_url = meetingService.getRtmpUrlByMeetingId(id);
        result.setCode(200);
        result.setMsg(rtmp_url);
        return result;
    }

//    @ResponseBody
//    @GetMapping("/getHotMeetings")
//    public Result getHotMeetings(){
//        Result result = new Result();
//        List<Meeting> meetingList = meetingService.getMeetings();
//        result.setCode(0);
//        result.setData(meetingList);
//        result.setMsg("查询成功");
//        return result;
//    }

    @ResponseBody
    @GetMapping("/updateMeetingHot/{id}")
    public Result updateMeetingHot(@PathVariable("id") String id){
        Result result = new Result();
        meetingService.updateMeetingHot(Integer.parseInt(id));
        result.setCode(200);
        result.setMsg("设置热门成功");
        return result;
    }
    @ResponseBody
    @GetMapping("/updateMeetingCold/{id}")
    public Result updateMeetingCold(@PathVariable("id") String id){
        Result result = new Result();
        meetingService.updateMeetingCold(Integer.parseInt(id));
        result.setCode(200);
        result.setMsg("设置冷门成功");
        return result;
    }


    @ResponseBody
    @GetMapping("/getHotMeetingsByWX")
    public Result getHotMeetingsByWX(){
        Result result = new Result();
        List<Meeting> meetingList = meetingService.getHotMeetings();
        result.setCode(200);
        result.setData(meetingList);
        result.setMsg("查询成功");
        return result;
    }

    @GetMapping("/getMeetingsByTime")
    @ResponseBody
    public Result getMeetingsByTime( @RequestParam int page,
                                       @RequestParam int limit,
                                       @RequestParam String start,
                                       @RequestParam String end) {
        Result result = new Result();
        int count = meetingService.getTimeCount(start, end);
        List<Meeting> meetingList = meetingService.getMeetingsByTime(page, limit, start, end);
        result.setCount(count);
        result.setData(meetingList);
        result.setCode(0);
        return result;
    }

    @DeleteMapping("/delMeeting/{id}")
    @ResponseBody
    public Result delActivity(@PathVariable("id") String id) {
        Result result = new Result();
        String[] s = id.split(",");
        for (int i = 0; i < s.length; i++) {
            meetingService.deleteMeetingById(Integer.parseInt(s[i]));
        }
        result.setCode(200);
        return result;
    }
    @ResponseBody
    @PostMapping("/getJoinUser")
    public Result getJoinUser(@RequestBody Map<String,Object> map){
        Result result = new Result();
        String userId =  map.get("userId").toString();
        String meetingId = map.get("meetingId").toString();
        User_meeting user_meeting = userService.findUserByUUidAndMeetingId(userId,meetingId);
        System.out.println(user_meeting);
        if (user_meeting==null){
            result.setMsg("0");
        }else{
            result.setMsg("1");
        }
        return result;
    }

    @ResponseBody
    @PostMapping("/sendJoin")
    public Result sendJoin(@RequestBody Map<String,Object> map){
        Result result = new Result();
        String userId =  map.get("userId").toString();
        String meetingId = map.get("meetingId").toString();
        String type = map.get("type").toString();
        User user = userService.findUserByUUid(userId);
        User_meeting userMeeting = userService.findUserByUUidAndMeetingId(userId,meetingId);
        if(userMeeting==null){
            User_meeting user_meeting = new User_meeting();
            user_meeting.setMeeting_id(Integer.parseInt(meetingId));
            user_meeting.setUser_id(userId);
            user_meeting.setIsJoin(1);
            userService.addUserMeeting(user_meeting);
        }else{
            userService.updateJoin(userId,meetingId);
        }

        if("1".equals(type)){
            String roomId = meetingService.getRoomIdByMeetingId(meetingId);
            result.setCode(200);
//            mailService.sendSimpleTextMailActual("报名结果","视频会议地址为:https://cqcq123.cn.utools.club/webrtc/。用户名请填写您的微信名，房间号为："+roomId,new String[]{user.getEmail()},new String[]{"18120691853@163.com"},null,null);
            mailService.sendSimpleTextMailActual("报名结果","视频会议地址为:https://www.cyansg.top/webrtc/user。用户名请填写您的微信名，房间号为："+roomId,new String[]{user.getEmail()},new String[]{"18120691853@163.com"},null,null);

        }
        return result;
    }

    @ResponseBody
    @PostMapping("/getMeetingsByJoin")
    public Result getMeetingsByJoin(@RequestBody Map<String,Object> map){
        Result result = new Result();
        String userId = map.get("userId").toString();
        List<Meeting> meetingList = meetingService.getMeetingsByJoin(userId);
        result.setData(meetingList);
        return result;
    }

    @ResponseBody
    @PostMapping("/getMeetingsByApply")
    public Result getMeetingsByApply(@RequestBody Map<String,Object> map){
        Result result = new Result();
        String userId = map.get("userId").toString();
        List<Meeting> meetingList = meetingService.getMeetingsByApply(userId);
        result.setData(meetingList);
        return result;
    }

    @ResponseBody
    @PostMapping("/sign")
    public Result sign(@RequestBody Map<String,Object> map){
        Result result = new Result();
        String roomId = map.get("roomId").toString();
        String uuid = map.get("uuid").toString();
        Meeting meeting = meetingService.findMeetingByRoomId(Integer.parseInt(roomId));
        int i = userService.isSign(String.valueOf(meeting.getId()),uuid);
        if (i==0){
            //未签到
            userService.sign(String.valueOf(meeting.getId()),uuid);
            result.setCode(200);
        }else{
            result.setCode(500);
        }
        return result;
    }


    /**
     * 收藏会议
     */
    @ResponseBody
    @PostMapping("/favorite")
    public Result favorite(@RequestBody Map<String,Object> map){
        Result result = new Result();
        String userId = map.get("userId").toString();
        String meetingId = map.get("meetingId").toString();
        // 收藏标识
        String flag = map.get("flag").toString();
        User_meeting userMeeting = meetingService.findUserMeetingById(userId,meetingId);
        if(userMeeting==null){
            meetingService.addUserMeetingFavorite(userId,meetingId);
        }
        int i = meetingService.updateFavorite(userId,meetingId,flag);
        if(i==1){
            result.setCode(200);
        }else{
            result.setCode(500);
        }
        return result;
    }
    /**
     * 获取收藏会议
     */
    @ResponseBody
    @PostMapping("/getFavorite")
    public Result getFavorite(@RequestBody Map<String,Object> map){
        Result result = new Result();
        String userId = map.get("userId").toString();
        String meetingId = map.get("meetingId").toString();
        User_meeting userMeeting = meetingService.findUserMeetingById(userId, meetingId);
        if(userMeeting==null){
            result.setMsg("0");
        }else{
            result.setMsg(userMeeting.getIsFavorite().toString());
        }
        return result;
    }

    @ResponseBody
    @PostMapping("/getMeetingsByFavorite")
    public Result getMeetingsByFavorite(@RequestBody Map<String,Object> map){
        Result result = new Result();
        String userId = map.get("userId").toString();
        List<Meeting> meetingList = meetingService.getMeetingsByFavorite(userId);
        result.setData(meetingList);
        return result;
    }
}
